﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.STaskCommand__生产管理;

namespace SmartProduction.Write.API.Application.CommandHandlers.STaskCommandHandler
{
    public class STaskAddCommandHandler : IRequestHandler<STaskAddCommand, APIResult<STask>>
    {
        private readonly IBaseRepository<STask> stakeRepository;
        private readonly IMapper mapper;
        private static int nextJobNodeNumber = 1;
        private static readonly object lockObject = new object();
        public STaskAddCommandHandler(IBaseRepository<STask> stakeRepository,IMapper mapper)
        {
            this.stakeRepository = stakeRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<STask>> Handle(STaskAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<STask> result=new APIResult<STask>();
            var model = mapper.Map<STask>(request);
            // 使用锁机制确保编号的唯一性和正确自增
            lock (lockObject)
            {
                model.TaskNode = "SC" + nextJobNodeNumber++;
            }
            model.CreatedBy = 1;
            model.CreatedTime = DateTime.Now;
            model.IsDelete = 0;
            model.Status = 0;
            var i = stakeRepository.AddAsync(model).Result;
            if (i > 0)
            {
                result.Code = APIEnums.添加成功;
                result.Msg = APIEnums.添加成功.ToString();
                result.data = model;
            }
            else
            {
                result.Code = APIEnums.添加失败;
                result.Msg = APIEnums.添加失败.ToString();
                result.data = model;
            }
            return await Task.FromResult(result);
        }
    }
}
